<template>
  <div class="content-container">
    <el-form label-width="auto" :inline="true" class="demo-form-inline">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="出库单号" class="full-width">
            <el-input v-model="filters.outId" placeholder="请输入出库单号" class="full-width"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="发货地" class="full-width">
            <el-input v-model="filters.origin" placeholder="请输入发货地" class="full-width"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="目的地" class="full-width">
            <el-input v-model="filters.destination" placeholder="请输入目的地" class="full-width"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="状态" class="full-width">
            <el-select v-model="filters.state" placeholder="请选择状态" class="full-width">
              <el-option label="全部" :value="null"></el-option>
              <el-option label="待分配物流公司" :value="0"></el-option>
              <el-option label="已分配物流公司" :value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="出库时间" class="full-width">
            <el-date-picker
                v-model="filters.outcomeDate"
                type="daterange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                class="full-width">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="预计到达时间" class="full-width">
            <el-date-picker
                v-model="filters.expectedDeliveryTime"
                type="daterange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                class="full-width">
            </el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item class="right full-width" label=" ">
            <el-button-group class="full-width">
              <el-button icon="search" type="primary" plain @click="search" style="width: 50%">查询</el-button>
              <el-button icon="refresh" @click="resetFilters" style="width: 50%">重置</el-button>
            </el-button-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="divider"></div>
    <el-row :gutter="20" class="action-buttons">
      <el-col :span="12">
        <el-button
            type="success"
            plain
            icon="truck"
            @click="openCarrierSelectionDialog"
            :disabled="!selectedOrders.length"
        >
          生成运输订单
        </el-button>
      </el-col>
    </el-row>
    <el-table :data="currentTableData"
              style="width: 100%; flex: 1"
              :header-cell-style="headerCellStyle"
              @selection-change="handleSelectionChange"
              :default-sort="{ prop: 'outId', order: 'descending' }">
      <el-table-column type="selection" width="50" v-if="showSelectionColumn" :selectable="isRowSelectable">
      </el-table-column>
      <el-table-column prop="outId" label="出库单号" min-width="140">
        <template v-slot="scope">
          <el-link type="primary" @click="openDetailDialog(scope.row.outId)">{{scope.row.outId}}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="warehouseId" label="发货仓库编号" min-width="100"></el-table-column>

      <el-table-column prop="origin" label="发货地" min-width="100"></el-table-column>

      <el-table-column prop="destination" label="目的地" min-width="100"></el-table-column>


      <el-table-column
          prop="deliveryCode"
          label="物流商ID"
          min-width="100">
        <template #default="{ row }">
          {{ row.deliveryCode || '无' }}
        </template>
      </el-table-column>

      <el-table-column
          prop="deliveryName"
          label="物流商姓名"
          min-width="100">
        <template #default="{ row }">
          {{ row.deliveryName || '无' }}
        </template>
      </el-table-column>

      <el-table-column prop="createdTime" label="创建时间" sortable min-width="100">
        <template v-slot="scope">
          <span>{{ formatDate(scope.row.createdTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="expectedDeliveryTime" label="预计到达日期" sortable min-width="120">
        <template v-slot="scope">
          <span>{{ formatDate(scope.row.expectedDeliveryTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="state" label="状态" min-width="100">
        <template v-slot="scope">
          <el-tag
              :type="getStateType(scope.row.state)"
              disable-transitions>
            {{ getStateLabel(scope.row.state) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" min-width="180">
        <template v-slot="scope">
          <el-button
              v-if="scope.row.state === 0"
              @click="openDialog(scope.row, true)"
              type="text"
              icon="EditPen"      style="font-size: 13px"
          >
            修改
          </el-button>
          <el-button
              @click="openOutBoundShowDialog(scope.row)"
              type="text"
              icon="Document"      style="font-size: 13px"
          >
            详情
          </el-button>
          <el-popconfirm
              v-if="scope.row.state === 0"
              width="200"
              confirm-button-text="确认"
              cancel-button-text="取消"
              icon-color="#626AEF"
              title="是否确定删除？"
              @confirm="handleDelete(scope.row)"
          >
            <template #reference>
              <el-button
                  type="text"
                  size="small"
                  icon="delete"          style="font-size: 13px"
              >
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        background
        layout="total, prev, pager, next"
        :total="total"
        :page-size="pageSize"
        v-model:current-page="currentPage"
        @current-change="handleCurrentChange"
        class="fixed-pagination">
    </el-pagination>
    <NewOutBoundDialog
        v-model="dialogVisible"
        @update:visible="dialogVisible = $event"
        :data="selectedOutBound"
        :isEdit="isEdit"
        @save="handleSave"
        visible/>

    <outBoundShowDialog
        v-model="outBoundShowVisible"
        :order="selectedOutBound"
        @close="outBoundShowVisible = false"
    />

    <outBound-detail-dialog v-model="detailDialogVisible" :order="selectedOutBound" @close="detailDialogVisible = false"
                              style="border-radius: 12px;
      display: flex;
      flex-direction: column;
      margin: 0 !important;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      max-height: calc(100% - 30px);
      max-width: calc(100% - 30px);
      justify-content: center;"/>

    <CarrierSelectionDialog
        v-model="carrierDialogVisible"
        :orders="selectedOrders"
        @close="handleCarrierDialogClose"
    />
  </div>
</template>

<script>
import {ref, reactive, onMounted} from 'vue';
import {ElMessage} from "element-plus";
import { getAddr } from '@/api/system/addr.js';
import {
  listOutBoundOrder,
  addOutBoundOrder,
  updateOutBoundOrder,
  deleteOutBoundOrder,
  getOutBoundOrderDetail,
} from '@/api/delivery/outBound.js';
import outBoundDetailDialog from "@/views/delivery/outBound/outBoundDetailDialog.vue";
import NewOutBoundDialog from "@/views/delivery/outBound/NewOutBoundDialog.vue";
import outBoundShowDialog from "@/views/delivery/outBound/outBoundShowDialog.vue";
import CarrierSelectionDialog from "@/views/delivery/outBound/CarrierSelectionDialog.vue";
export default {
  components: {outBoundDetailDialog,NewOutBoundDialog,outBoundShowDialog, CarrierSelectionDialog},
  setup() {
    const filters = reactive({
      outId : '',
      origin : '',
      destination : '',
      outcomeDate : [],
      expectedDeliveryTime : [],
      state : null
    });

    const selectedOutBound = ref({});
    const isEdit = ref(false);

    const currentTableData = ref([]);
    const total = ref(0);
    const pageSize = ref(10);
    const currentPage = ref(1);

    const carrierDialogVisible = ref(false); // 控制物流商选择对话框显示
    const selectedOrder = ref({}); // 当前选中的订单
    const selectedOrders = ref([]);

    // 查询客户地址信息
    const fetchCustomerAddresses = async () => {
      try {
        const response = await listAddr({}); // 查询所有地址信息
        return response.data || [];
      } catch (error) {
        ElMessage.error("获取客户地址信息失败");
        return [];
      }
    };


    const handleCarrierDialogClose = () => {
      carrierDialogVisible.value = false;
    };

    const getStateType = (state) => {
      if (state === '未分配运输订单' || state === '送往加工' || state === '送往配送') {
        return 'danger';
      } else if (state === '已分配运输订单') {
        return 'warning';
      } else {
        return 'info'; // 默认类型
      }
    };

    const getStateLabel = (state) => {
      if (state === '送往加工' || state === '送往配送') {
        return '未分配运输订单';
      }
      return state; // 直接返回状态字符串作为标签内容
    };


    const openCarrierSelectionDialog = () => {
      console.log('Selected Orders:', selectedOrders.value);
      if (selectedOrders.value.length > 0) {
        carrierDialogVisible.value = true;
      } else {
        ElMessage.warning('请先选择要生成运输订单的行');
      }
    };

    const dialogVisible = ref(false);
    const openDialog = (outBound, edit) => {
      dialogVisible.value = true;
      isEdit.value = edit;
      selectedOutBound.value = outBound || {};
    };

    const outBoundShowVisible = ref(false);

    const openOutBoundShowDialog = (order) => {
      selectedOutBound.value = order;
      outBoundShowVisible.value = true;
      console.log(order);
    };

    const handleSave = async (OrderData) => {
      try {
        if (isEdit.value) {
          await updateOutBoundOrder(OrderData);
        } else {
          await addOutBoundOrder(OrderData);
        }

        dialogVisible.value = false;
        search();
      } catch (error) {
        console.error('保存失败:', error);
      }
    };

    const handleDelete = async (row) => {
      try {
        await deleteOutBoundOrder(row.outId);
        if (currentTableData.value.length === 1 && currentPage.value > 1) {
          currentPage.value -= 1;
        }
        search();
      } catch (error) {
        console.error('删除失败:', error);
      }
    };

    const detailDialogVisible = ref(false);
    const openDetailDialog = async (order) => {
      try {
        console.log('Order details:', order);
        selectedOutBound.value = order;
        detailDialogVisible.value = true;
      } catch (error) {
        ElMessage.error('获取出库单详情失败');
      }
    };

    const formatDate = (value) => {
      if (!value) return '';
      const date = new Date(value);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    };
    const search = async () => {
      const query = {
        outId: filters.outId,
        origin: filters.origin,
        destination: filters.destination,
        state: filters.state,
        departStartDate: filters.outcomeDate.length ? formatDate(filters.outcomeDate[0]) : null,
        departEndDate: filters.outcomeDate.length ? formatDate(filters.outcomeDate[1]) : null,
        arriveStartDate: filters.expectedDeliveryTime.length ? formatDate(filters.expectedDeliveryTime[0]) : null,
        arriveEndDate: filters.expectedDeliveryTime.length ? formatDate(filters.expectedDeliveryTime[1]) : null,
        page: currentPage.value,
        pageSize: pageSize.value,
      };

      try {
        // **查询出库订单**
        const response = await listOutBoundOrder(query);
        let orders = response.data || [];
        total.value = response.total;

        // **获取并替换每个 destination 的详细地址**
        for (const order of orders) {
          if (order.destination) {
            try {
              const addressResponse = await getAddr(order.destination); // 查询单个地址
              const addressData = addressResponse.data;

              if (addressData) {
                order.destination = `${addressData.country || ''} ${addressData.state || ''} ${addressData.city || ''} ${addressData.district || ''} ${addressData.streetAddress || ''}`.trim();
              }
            } catch (error) {
              console.error(`获取地址信息失败 (addressId: ${order.destination})`, error);
            }
          }
        }

        // **更新表格数据**
        currentTableData.value = orders;

      } catch (error) {
        ElMessage.error("获取出库订单信息失败");
      }
    };


    // 表格主选择框选中时触发
    const handleSelectionChange = (rows) => {
      selectedOrders.value = rows;
    };

    const resetFilters = () => {
      filters.outId = '';
      filters.origin = '';
      filters.destination = '';
      filters.outcomeDate = [];
      filters.expectedDeliveryTime = [];
      filters.state = null;
      currentPage.value = 1;
      search();
    };
    const handleCurrentChange = (page) => {
      currentPage.value = page;
      search();
    };
    onMounted(() => {
      search();
    });

    const showSelectionColumn = computed(() => {
      return currentTableData.value.some(outBound =>
          outBound.state === '未分配运输订单' ||
          outBound.state === '送往加工' ||
          outBound.state === '送往配送'
      );
    });

    const isRowSelectable = (row) => {
      if (row.state !== '未分配运输订单' && row.state !== '送往加工' && row.state !== '送往配送') {
        return false;
      }

      if (selectedOrders.value.length === 0) {
        return true;
      }

      const firstSelectedOrder = selectedOrders.value[0];
      return (
          row.origin === firstSelectedOrder.origin &&
          row.destination === firstSelectedOrder.destination &&
          row.warehouseId === firstSelectedOrder.warehouseId
      );
    };

    return {
      filters,
      selectedOutBound,
      currentTableData,
      total,
      pageSize,
      currentPage,
      dialogVisible,
      outBoundShowVisible,
      openOutBoundShowDialog,
      openDialog,
      handleSave,
      handleSelectionChange,
      handleDelete,
      detailDialogVisible,
      openDetailDialog,
      formatDate,
      search,
      resetFilters,
      handleCurrentChange,
      isEdit,
      showSelectionColumn,
      isRowSelectable,
      selectedOrders,
      carrierDialogVisible,
      selectedOrder,
      openCarrierSelectionDialog,
      handleCarrierDialogClose,
      getStateType,
      getStateLabel,
      fetchCustomerAddresses,
    };
  }
};
</script>

<style scoped>
.content-container {
  background-color: white;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  max-width: calc(100% - 40px);
  border-radius: 8px;
  position: relative;
  display: flex;
  flex-direction: column;
  margin-left: 20px;
  margin-top: 15px;
}

.divider {
  height: 1px;
  background-color: #eaeaea;
  margin-top: 0;
  margin-bottom: 12px;
}

.dialog-footer {
  text-align: center;
}

.action-buttons {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.right-aligned {
  display: flex;
  justify-content: flex-end;
}

.el-segmented {
  width: 100%;
}

.el-form-item.right:deep(.el-form-item__content) {
  justify-content: end;
}

.demo-form-inline {
  display: flex;
  flex-wrap: wrap;
  background: white;
}

.full-width {
  width: 100%;
}

.fixed-pagination {
  position: relative;
  right: 0;
  align-self: end;
  margin-top: 20px;
}
</style>
